//用绝对路径保证不出错误,path是nodejs里面的基本包,用来处理路径
const path = require('path')
const HTMLPlugin = require('html-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader');
const webpack = require('webpack');
const ExtractPlugin = require('extract-text-webpack-plugin')

const isDev = process.env.NODE_ENV === 'development'



//index.js是入口文件，vue是组件不能直接挂载到html里面
const config={
	target:'web',
	//__dirname这个文件所在目录的地址，即根目录，表示这个路径和后面的路径拼接起来，形成绝对路径，保证绝对可以访问到我们想要访问的文件
	entry: path.join(__dirname, 'src/index.js'),
	output:{
		filename: 'bundle.[hash:8].js',//输出路径
		path: path.join(__dirname, 'dist')
	},
	 module: {
	    rules: [
	      {
	        test: /\.vue$/,
	        loader: 'vue-loader'
	      },
	      {
	        test: /\.jsx$/,
	        loader: 'babel-loader'
	      },
	      {
	        test: /\.(gif|jpg|jpeg|png|svg)$/,
	        //loader:'css-loader' //css-loader只是帮我们处理css文件
	        use: [//帮我们把css写到html里面去
	          {
	            loader: 'url-loader',
	            options: {
	              limit: 1024,
	              name: '[name]-aaa.[ext]'
	            }
	          }
	        ]
	      }
	    ]
	}
	 ,
plugins: [
    // make sure to include the plugin for the magic
    new VueLoaderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: isDev ? '"development"' : '"production"'
      }
    }),
    new HTMLPlugin()
  ]
}
//配置文件要同时用在正式环境和开发环境，所以配置要根据不同环境去做判断，
//设置环境变量来标识是开发环境还是正式环境

if(isDev){
	config.module.rules.push({
	    test: /\.styl/,
	    use: [
	      'style-loader',
	      'css-loader',
	      {
	        loader: 'postcss-loader',
	        options: {
	          sourceMap: true,
	        }
	      },
	      'stylus-loader'
	    ]
	  })
	config.devtool = '#cheap-module-eval-source-map'
	config.devServer = {
	    port: 8000,
	    host: '0.0.0.0',
	    overlay: {
	      errors: true,
	    },
	   hot:true
	  }
	config.plugins.push(
	    new webpack.HotModuleReplacementPlugin(),
	    new webpack.NoEmitOnErrorsPlugin()
	  )
}else{
	config.entry = {
	    app: path.join(__dirname, 'src/index.js'),
	    vendor: ['vue']
	  }
	config.output.filename = '[name].[chunkhash:8].js'
	config.module.rules.push({
	      test: /\.styl/,
	      use: ExtractPlugin.extract({
	        fallback: 'style-loader',
	        use: [
	          'css-loader',
	          {
	            loader: 'postcss-loader',
	            options: {
	              sourceMap: true,
	            }
	          },
	          'stylus-loader'
	        ]
	      })
	    },
	  )
	config.plugins.push(
	    new ExtractPlugin('styles.[contentHash:8].css'),
	    new webpack.optimize.CommonsChunkPlugin({
	      name: 'vendor'
	    }),
	    new webpack.optimize.CommonsChunkPlugin({
	      name: 'runtime'
	    })
    )
}

module.exports = config